import React, { useState } from "react"
import { connect } from "react-redux"
import instance from "../../utils/instance"
import { getCookie } from "../../utils/cookie"
import "./AnswerInput.css"


function AnswerInput(props) {
    const [content, setContent] = useState("")
    const submitAnswer = (e) => {
        let token = getCookie("token")
        instance.defaults.headers.common['Authorization'] = "Bearer " + token
        instance.post(`/answers/${props.questionId}`, {
            content
        }).then(data => {
            if (data.data.errno === 0) {
                alert("回答成功!")
            } else {
                alert("回答失败，请重新尝试!")
            }
        }).catch(err => {
            alert("回答失败，请重新尝试!")
        })
    }
    return (
        <div className="answerInput">
            <div className="answerer">
                <img src={props.userInfo.avatar_url} alt="" />
                <p>{props.userInfo.username}</p>
            </div>
            <div className="answer_textarea">
                <textarea placeholder="请输入您的回答" onChange={(e) => { setContent(e.target.value) }} />
            </div>
            <div className="submit_answer">
                <input type="button" value="提交" onClick={(e) => { submitAnswer(e) }} />
            </div>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        userInfo: state.home.userInfo
    }
}

export default connect(mapStateToProps, null)(AnswerInput)